<?php

class Online extends Think
{
    protected $lifeTime = '1800';
    protected $sessionId = '';
    protected $dao;

    public function __construct(&$params = '')
    {
        $this->lifeTime = 1800;
        if (cookie('onlineid')) {
            $this->sessionId = cookie('onlineid');
        } else {
            $this->sessionId = substr(MD5(session_id()), 0, 32);
            cookie('onlineid', $this->sessionId, 0);
        }

        $this->dao = M('Online');
        $this->write($this->sessionId);
        $this->gc($this->lifeTime);
    }

    public function open($savePath, $sessName)
    {
        return true;
    }

    public function close()
    {
        return $this->gc($this->lifetime);
    }

    public function read($sessID)
    {
        $r = $this->dao->find($sessID);
        return $r ? $r['data'] : '';
    }

    public function write($sessID, $sessData = '')
    {
        $ip = get_client_ip();
        $username = cookie('username') ? cookie('username') : '';
        $group_id = cookie('group_id') ? intval(cookie('group_id')) : 0;
        $sessiondata = array(
            'session_id' => $sessID,
            'user_id'    => intval(cookie('user_id')),
            'username'  => $username,
            'ip'        => $ip,
            'lastvisit' => time(),
            'group_id'   => $group_id,
            'data'      => '',
        );
        return $this->dao->add($sessiondata, '', true);
    }


    public function destroy($sessID)
    {
        return $this->dao->delete($this->sessionId);
    }

    public function gc($sessMaxLifeTime)
    {
        $expiretime = time() - $sessMaxLifeTime;
        $r = $this->dao->where(" lastvisit < $expiretime")->delete();
        return $r;
    }

}